package com.cssw.fyzb.tps.api.auth;

import com.cssw.fyzb.tps.config.auth.AccessTokenConfig;
import com.cssw.fyzb.tps.config.auth.Sign;
import com.cssw.fyzb.tps.exception.BizException;
import com.cssw.fyzb.tps.service.auth.tecent.AccessToken;
import com.cssw.fyzb.tps.service.auth.tecent.NONCETicket;
import com.cssw.fyzb.tps.service.auth.tecent.UserAuthInfo;
import com.cssw.fyzb.tps.util.SignUtil;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplelock.SimpleLock;
import com.ydn.simplelock.SimpleLockFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 后台送身份信息
 *
 * @Author zhouxu
 * @create 2020-09-14 20:54
 */
@Function(description = "后台送身份信息", parameters = {
        @Parameter(name = "userName", type = Type.String, description = "姓名", required = true),
        @Parameter(name = "idNo", type = Type.String, description = "身份证号码", required = true),
        @Parameter(name = "userId", type = Type.String, description = "用户ID", required = true),
        @Parameter(name = "orderNo", type = Type.String, description = "订单号", required = true),
        @Parameter(name = "nonceStr", type = Type.String, description = "随机数", required = true),

})
@Component
public class TecentFaceAuthSend implements Action {

    private static final Logger logger = LoggerFactory.getLogger(TecentFaceAuthSend.class);

    @Autowired
    private AccessToken accessToken;

    @Autowired
    private NONCETicket nonceTicket;

    @Autowired
    private UserAuthInfo userAuthInfo;

    @Autowired
    private SimpleLockFactory simpleLockFactory;


    @Override
    public Response execute(Request request) {
        // 用户名
        String userName = request.getString("userName");
        // 身份证号码
        String idNo = request.getString("idNo");
        // 用户ID
        String userId = request.getString("userId");
        // uuid
        String orderNo = request.getString("orderNo");
        // 随机数
        String nonceStr = request.getString("nonceStr");

        SimpleLock simpleLock = simpleLockFactory.getLock(AccessToken.KEY_PREX + accessToken.getAppId());
        AccessTokenConfig accessHttpResult = null;

        try {

            simpleLock.acquire();
            // 获取 Access Token
            accessHttpResult = accessToken.getAccessToken();

        } catch (BizException be) {
            logger.error(be.getErrMsg(), be.getErrCode());
            return Response.fail(be.getErrMsg(), be.getErrCode());
        } catch (Exception e) {
            logger.error("获取 access token 失败:", e);
            return Response.fail(e);
        } finally {
            try {
                simpleLock.release();
            } catch (Exception e) {
                logger.error("", e);
            }
        }

        logger.debug("AccessToken 返回：" + accessHttpResult.toString());
        String accessToken = accessHttpResult.getAccessToken();
        NONCETicket.HttpResult nonceHttpResult = null;


        try {
            // 获取 NONCE Ticket
            nonceHttpResult = nonceTicket.getNONCETicket(userId, accessToken);
        } catch (BizException be) {
            logger.error(be.getErrMsg(), be.getErrCode());
            return Response.fail(be.getErrMsg(), be.getErrCode());
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return Response.fail(e);
        }

        List<NONCETicket.Ticket> tickets = nonceHttpResult.getTickets();
        NONCETicket.Ticket ticket = tickets.get(0);
        logger.debug("NONCETicket 返回:" + ticket.toString());
        String ticketValue = ticket.getValue();

        // 数字签名
        String sign = getSign(
                new Sign(userAuthInfo.getWebankAppId(), userId, userAuthInfo.getVersion(), ticketValue, nonceStr)
        );


        UserAuthInfo.HttpResult userHttpResult = null;

        try {
            // 发送用户身份信息
            userHttpResult = userAuthInfo.sendUserInfo(
                    userId, userName, idNo, nonceStr, orderNo, ticketValue, sign
            );
        } catch (BizException be) {
            logger.error(be.getErrMsg(), be.getErrCode());
            return Response.fail(be.getErrMsg(), be.getErrCode());
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return Response.fail(e);
        }

        return Response.success().put("data", userHttpResult).put("sign", sign)
                .put("license", userAuthInfo.getLicense())
                .put("version", userAuthInfo.getVersion())
                .put("appId", userAuthInfo.getWebankAppId());
    }


    private String getSign(Sign sign) {
        List<String> values = new ArrayList<>();
        values.add(sign.getAppId());
        values.add(sign.getUserId());
        values.add(sign.getVersion());
        values.add(sign.getNonce());
        logger.debug("数字签名参数:" + sign.toString());
        return SignUtil.sign(values, sign.getTicketValue());
    }


}
